import React, { useState, useEffect, useCallback, useRef } from 'react'
import { SessionList } from './SessionList'
import { Chat } from './Chat'
import { Settings } from './Settings'
import { ModelConfigWidget } from './ModelConfigWidget'
import { CompactRoleSelector } from './ui/RoleSelector'
import { useChatStore } from '../stores/chatStore'
import { useAuthStore } from '../stores/authStore'

// 模型参数预设类型
type ModelPreset = 'precise' | 'balanced' | 'creative'

// 角色类型 (从 RoleSelector 导入)
import type { RoleType } from './ui/RoleSelector'

export const MainLayout: React.FC = () => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [showSettings, setShowSettings] = useState(false)
  const [sidebarWidth, setSidebarWidth] = useState(320) // 默认320px
  const [isDragging, setIsDragging] = useState(false)
  const [modelPreset, setModelPreset] = useState<ModelPreset>('balanced')
  const [currentRole, setCurrentRole] = useState<RoleType>('emma')
  const sidebarRef = useRef<HTMLDivElement>(null)
  const { currentSession } = useChatStore()
  const { user, logout } = useAuthStore()

  // 模型参数预设配置
  const modelPresets = {
    precise: { label: '⚡ 精准', temperature: 0.3, top_p: 0.8, description: '准确度优先，适合分析和解答' },
    balanced: { label: '⚖️ 平衡', temperature: 0.7, top_p: 0.9, description: '平衡创意与准确性' },
    creative: { label: '🎨 创意', temperature: 0.9, top_p: 0.95, description: '创意优先，适合创作和头脑风暴' }
  }


  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768)
    }
    
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  // 处理侧边栏拖拽调整
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    e.preventDefault()
    setIsDragging(true)
    
    const startX = e.clientX
    const startWidth = sidebarWidth
    
    const handleMouseMove = (e: MouseEvent) => {
      const newWidth = startWidth + (e.clientX - startX)
      // 限制宽度范围：最小250px，最大500px
      const constrainedWidth = Math.max(250, Math.min(500, newWidth))
      setSidebarWidth(constrainedWidth)
    }
    
    const handleMouseUp = () => {
      setIsDragging(false)
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
    
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
  }, [sidebarWidth])

  return (
    <div className="mindmate-app">
      {/* 顶部导航栏 */}
      <div className="fixed top-0 left-0 right-0 h-15 bg-white border-b border-gray-200 flex items-center justify-between px-5 z-50" style={{
        height: '60px',
        boxShadow: 'var(--shadow-sm)'
      }}>
        {/* Logo区域 */}
        <div className="flex items-center gap-5">
          <div className="flex items-center gap-2">
            <span className="text-2xl">🧠</span>
            <span style={{
              fontSize: 'var(--text-xl)',
              fontWeight: 600,
              color: 'var(--primary-600)'
            }}>MindMate</span>
          </div>
          
          {/* 中间功能区 */}
          <div className="flex items-center gap-4">
            {/* 模型配置组件 */}
            <ModelConfigWidget />

            {/* 角色选择器 */}
            <CompactRoleSelector 
              currentRole={currentRole}
              onRoleChange={setCurrentRole}
            />
          </div>
        </div>

        {/* 右侧操作区 */}
        <div className="flex items-center gap-3">
          <button 
            onClick={() => setShowSettings(true)}
            className="p-2 rounded-md hover:bg-gray-100 transition-colors"
            title="设置"
          >
            ⚙️
          </button>
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium" style={{
              background: 'var(--primary-100)',
              color: 'var(--primary-700)'
            }}>
              {user?.username?.charAt(0) || 'U'}
            </div>
          </div>
        </div>
      </div>

      {/* 主容器 */}
      <div className="mindmate-container pt-15" style={{ paddingTop: '60px' }}>
        {/* 设置弹窗 */}
        {showSettings && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 modal-overlay">
            <div className="bg-white rounded-lg max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto modal-content" style={{
              borderRadius: 'var(--radius-lg)'
            }}>
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <h2 style={{ fontSize: 'var(--text-xl)', fontWeight: 600 }}>API配置</h2>
                <button
                  onClick={() => setShowSettings(false)}
                  className="text-gray-500 hover:text-gray-700 text-2xl"
                >
                  ×
                </button>
              </div>
              <div className="p-4">
                <Settings />
              </div>
            </div>
          </div>
        )}

        {/* 左侧会话列表 */}
        <div className="w-70 bg-white border-r border-gray-200 flex-shrink-0" style={{ width: '280px' }}>
          <SessionList 
            className="h-full"
            onSessionSelect={() => {
              if (isMobile) setIsMobileMenuOpen(false)
            }}
          />
        </div>

        {/* 主对话区域 */}
        <div className="flex-1 flex flex-col">
          <Chat 
            showSettings={showSettings}
            setShowSettings={setShowSettings}
            logout={logout}
            currentRole={currentRole}
          />
        </div>

        {/* 右侧面板（可选，桌面端显示） */}
        {!isMobile && (
          <div className="w-80 bg-white border-l border-gray-200 flex-shrink-0" style={{ width: '320px' }}>
            <div className="h-full p-4">
              {/* 智能摘要 */}
              <div className="mb-6">
                <div className="flex items-center gap-2 mb-3">
                  <span style={{ fontSize: 'var(--text-base)', fontWeight: 600 }}>📝 智能摘要</span>
                </div>
                <div className="p-5 rounded-xl shadow-lg hover:shadow-xl transition-all" style={{
                  background: 'linear-gradient(135deg, var(--accent-500) 0%, var(--accent-600) 100%)',
                  color: 'white',
                  borderRadius: 'var(--radius-xl)',
                  boxShadow: '0 4px 12px rgba(249, 115, 22, 0.15)'
                }}>
                  <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: '8px' }}>对话要点</div>
                  <div style={{ fontSize: 'var(--text-sm)', opacity: 0.9 }}>
                    当前对话暂无内容，开始聊天后将自动生成智能摘要。
                  </div>
                </div>
              </div>

              {/* 快捷操作 */}
              <div>
                <div style={{ fontSize: 'var(--text-base)', fontWeight: 600, marginBottom: '12px' }}>⚡ 快捷操作</div>
                <div className="space-y-2">
                  {[
                    { icon: '💾', text: '保存对话' },
                    { icon: '📤', text: '分享' },
                    { icon: '🔄', text: '清空' },
                    { icon: '⚙️', text: '设置' }
                  ].map((item, index) => (
                    <button 
                      key={index}
                      className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all hover:scale-[1.02] text-left" 
                      style={{ borderRadius: 'var(--radius-md)', animationDelay: `${index * 0.1}s` }}
                    >
                      <span>{item.icon}</span>
                      <span style={{ fontSize: 'var(--text-sm)' }}>{item.text}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 移动端遮罩层和侧边栏 */}
        {isMobile && (
          <>
            {/* 汉堡菜单按钮 */}
            <button
              onClick={() => setIsMobileMenuOpen(true)}
              className="fixed top-4 left-4 z-40 p-2 bg-white rounded-lg shadow-md"
              style={{ top: '70px' }}
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>

            {/* 移动端侧边栏 */}
            {isMobileMenuOpen && (
              <>
                <div 
                  className="fixed inset-0 bg-black bg-opacity-50 z-40"
                  onClick={() => setIsMobileMenuOpen(false)}
                />
                <div className="fixed left-0 top-0 h-full w-80 bg-white z-50" style={{ top: '60px' }}>
                  <SessionList 
                    className="h-full"
                    onSessionSelect={() => setIsMobileMenuOpen(false)}
                  />
                </div>
              </>
            )}
          </>
        )}
      </div>
    </div>
  )
}